<?php

namespace App\Kuafu\Shop\Model;

use App\Kuafu\Base\Model\BaseModel;
use App\Kuafu\Base\Model\Traits\KfSoftDeletes;

class ShopDistributionBillRecordModel extends BaseModel
{
    use KfSoftDeletes;

    protected $connection = 'mysql';
    protected $table      = 'shop_distribution_bill_record';
    protected $primaryKey = 'id';
    protected $fillable   = [
        'id',
        'shopId',
        'distributionId',
        'settlementCycleTime',
        'amount',
        'brokerage',
        'isDeleted',
        'updatedByUid',
        'createdByUid',
        'updatedAt',
        'createdAt',
    ];

    public static function batchAddData(array $data): bool
    {
        return self::query()->insert($data);
    }

    public static function getBillRecordByShopId(int $shopId, int $distributionId, int $startTime = 0, int $endTime = 0): int
    {
        return self::query()
                   ->where('shopId', $shopId)
                   ->when($distributionId, function ($query) use ($distributionId) {
                       $query->where('distributionId', $distributionId);
                   })
                   ->when($startTime && $endTime, function ($query) use ($startTime, $endTime) {
                       $query->whereBetween('settlementCycleTime', [$startTime, $endTime]);
                   })
                   ->sum('brokerage');
    }
}
